package com.ca.ridersclubapplication.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;

import com.ca.ridersclubapplication.ChatActivity;
import com.ca.ridersclubapplication.MainActivity;
import com.ca.ridersclubapplication.R;
import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.request.AfterExecutor;
import com.ca.ridersclubapplication.request.FileRequester;
import com.ca.ridersclubapplication.request.MessageRequester;
import com.ca.ridersclubapplication.request.dto.AccountDto;
import com.ca.ridersclubapplication.request.dto.ChatMessageDto;
import com.ca.ridersclubapplication.request.dto.MsgListDto;
import com.ca.ridersclubapplication.request.dto.Result;
import com.ca.ridersclubapplication.service.MessageService;
import com.ca.ridersclubapplication.util.ImageUtils;
import com.ca.ridersclubapplication.util.TimeUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;

public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageHolder> {

    private final Activity activity;

    private List<MsgListDto> list;
    private final List<Badge> badgeList = new ArrayList<>();

    public MessageAdapter(Activity activity, List<MsgListDto> list) {
        this.activity = activity;
        this.list = list == null ? new ArrayList<>() : list;
    }

    @NonNull
    @Override
    public MessageHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.message_item_layout, parent, false);
        return new MessageHolder(view);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onBindViewHolder(@NonNull MessageHolder holder, int position) {

        if (position == 0) {
            badgeList.clear();
        }
        badgeList.add(holder.badge);

        MsgListDto dto = list.get(position);

        Long targetId = dto.getTargetId();
        ImageUtils.loadCircleImage(holder.headerView.getContext(), FileRequester.HEADER_BY_ID_BASE_URL + targetId, holder.headerView);
        holder.nameView.setText(dto.getTargetNickName());
        holder.timeView.setText(TimeUtils.parseShowDateTime(dto.getTime()));
        holder.contentView.setText(dto.getContent());

        if (dto.getUnReadCount() != 0) {
            long count = dto.getUnReadCount();
            holder.badge
                    .setBadgeNumber((int) count)
                    .setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {
                        @Override
                        public void onDragStateChanged(int i, Badge badge, View view) {
                            if (Badge.OnDragStateChangedListener.STATE_SUCCEED == i) {
                                //  删除未读消息提示
                                MessageService.unReadCount -= dto.getUnReadCount();
                                badge.setBadgeNumber(0);
                                MessageRequester.setRead(activity, targetId, null);
                            }
                        }
                    });

        }

        //  点击事件
        holder.parent.setOnClickListener(v -> {
            Intent intent = new Intent(activity, ChatActivity.class);
            intent.putExtra("targetId", targetId);
            activity.startActivity(intent);
        });

        //  长按删除
        Dialog dialog = new Dialog(activity);
        @SuppressLint("InflateParams")
        View dialogView = LayoutInflater.from(activity).inflate(R.layout.delete_message_dialog_layout, null);
        TextView cancelButton =  dialogView.findViewById(R.id.btn_cancel);
        TextView sureButton =  dialogView.findViewById(R.id.btn_sure);
        cancelButton.setOnClickListener(v -> {
            dialog.dismiss();
        });
        final int i = position;
        sureButton.setOnClickListener(v -> {
            MessageRequester.deleteMsgListByTarget(activity, targetId, new AfterExecutor<String>() {
                @Override
                public void execute(Result<String> result) {
                    if (result.isSuccess()) {
                        long count = MessageService.unReadCount - dto.getUnReadCount();
                        int c = (int) count;
                        list.remove(i);
                        notifyItemRemoved(i);
                        Handler handler = new Handler();
                        handler.postDelayed(() -> {
                            MessageService.setUnReadCount(c);
                        }, 500);
                    }
                }
            });
            dialog.dismiss();
        });
        dialog.setContentView(dialogView);
        holder.parent.setOnLongClickListener(v -> {

            dialog.show();

            return false;
        });
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @SuppressLint("NotifyDataSetChanged")
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void setList(List<MsgListDto> list) {

        if (list == null) {
            list = new ArrayList<>();
        }

        for (MsgListDto dto : list) {
            Log.e("Dto", String.valueOf(dto));
        }

        //  按时间排序
        list.sort(new Comparator<MsgListDto>() {
            @Override
            public int compare(MsgListDto o1, MsgListDto o2) {
                return o2.getTime().compareTo(o1.getTime());
            }
        });

        this.list = list;
        notifyDataSetChanged();
    }

    public void setReadAll() {
        for (Badge badge : badgeList) {
            badge.setBadgeNumber(0);
        }
    }

    public static class MessageHolder extends RecyclerView.ViewHolder {

        public ConstraintLayout parent;
        public ImageView headerView;
        public TextView nameView;
        public TextView contentView;
        public TextView timeView;

        public Badge badge;
        public FrameLayout fl;
        public TextView dotTargetView;

        public MessageHolder(@NonNull View itemView) {
            super(itemView);
            parent = itemView.findViewById(R.id.cl_parent);
            headerView = itemView.findViewById(R.id.iv_header);
            nameView = itemView.findViewById(R.id.tv_name);
            contentView = itemView.findViewById(R.id.tv_content);
            timeView = itemView.findViewById(R.id.tv_time);

            fl = itemView.findViewById(R.id.fl);
            dotTargetView = itemView.findViewById(R.id.dot_target);

            badge = new QBadgeView(itemView.getContext())
                    .bindTarget(dotTargetView)
                    .setBadgeTextSize(8, true)
                    .setExactMode(false)
                    .setShowShadow(true);
        }
    }
}
